package com.edu.whty.common.tools;

import com.edu.whty.common.constants.MsgConstants;
import com.edu.whty.entity.teacherassistant.ResultMessage;
import org.apache.commons.httpclient.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 * 上传文件
 * 
 * @date 2014年12月18日
 */
public class UploadFileUtil {

	private static Logger logger = LoggerFactory.getLogger(UploadFileUtil.class);
	
	private static Properties properties = new Properties();
	
	private static final String filePathCfg = "filepath.properties";
	
	public static final String PIC_URL = "pic_url";
	
	/**
	 * 工程服务器网址
	 */
	public static final String PROJECT_HTTP = "project_http";
	/**
	 * 文件服务器网址
	 */
	private static final String FILE_HTTP = "file_http";
	/**
	 * 文件服务器映射地址
	 */
	private static final String FILE_DOCBASE = "file_docbase";
	
	/**
	 * pc端上传微课地址
	 */
	public static final String PATH_WEIKE_PC = "weike_pc";
	
	/**
	 * web端上传微课地址
	 */
	public static final String PATH_WEIKE_WEB = "weike_web";
	
	/**
	 * 课堂测试文件地址
	 */
	public static final String PATH_KT_EXAM = "kt_exam";
	/**
	 * 个性化上传文件web地址
	 */
	public static final String PATH_TUTORIAL_WEB = "tutorial_web";
	/**
	 * 个性化上传文件pc地址
	 */
	public static final String PATH_TUTORIAL_PC = "tutorial_pc";
	/**
	 * 我的教材上传文件web地址
	 */
	public static final String PATH_TEACHMATERIAL="tbook_web";
	
	/**
	 * 客户端软件仓库地址
	 */
	public static final String PATH_CLIENT_SOFT = "client_soft";
	
	/**
	 * 用户头像地址
	 */
	public static final String PATH_USER_LOGO = "user_logo";
	
	/**
	 * 默认用户头像地址
	 */
	public static final String DEFAULT_USER_LOGO = "default_user_logo";
	
	/**
	 * 微课默认地址
	 */
	public static final String WEIKE_ICO = "weike_ico";
	
	/**
	 * 图片格式
	 */
	public static final String IMAGE_FORMAT = "bmp,png,jpeg,gif,jpg";
	
	static {
		try {
			if(properties.isEmpty()){
				InputStream is = SysConfig.class.getClassLoader().getResourceAsStream(filePathCfg);
				properties.load(is);
			}
			logger.info("加载文件目录配置'" + filePathCfg + "'成功！");
		} catch (FileNotFoundException e) {
			logger.error("文件目录配置文件不存在！",e);
		} catch (IOException e) {
			logger.error("读取文件目录配置文件IO错误！",e);
		}
	}
	
	/**
	 * 获取文件上传目录
	 * 
	 * @param key
	 * @return
	 */
	public static String getFilePath(String key){
		return properties.getProperty(key);
	}
	
	
	/**
	 * 处理Request的文件
	 * @param rootPath 文件根目录
	 * @param request 请求Request
	 * @return
	 */
	public static ResultMessage uploadFileByRequest(String rootPath, HttpServletRequest request) {
		ResultMessage result = new ResultMessage();
		String relativePath = DateUtil.formatDate(new Date(), "yyyyMMdd");
		String savePath = rootPath +"/"+ relativePath;
		logger.info(request.getRemoteHost()+" : 开始上传文件,路径是: "+savePath);
		File filePath = new File(savePath);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		try {
			MultipartHttpServletRequest multiReq = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiReq.getFileNames();
			Map<String, Object> map = MapUtils.newHashMap();
			List<String> fileList = new ArrayList<String>();
			List<String> oriFileList = new ArrayList<String>();
			while (iter.hasNext()) {
				MultipartFile file = multiReq.getFile(iter.next());
				String orgFileName = file.getOriginalFilename();
				if (!orgFileName.isEmpty()) {
					String extName = FileUtil.getFileType(orgFileName);
					String newFileName = UUIDUtils.getRandomUUID() + "." + extName;
					File saveFile = new File(filePath, newFileName);
					fileList.add(newFileName);
					oriFileList.add(orgFileName);
					file.transferTo(saveFile);
				}
			}
			if (fileList.size() > 0) {
				map.put("filePath", savePath);
				map.put("fileList", fileList);
				map.put("oriFileList", oriFileList);
				result.setResult(MsgConstants.SUCCESS_CODE);
				result.setResultMsg("上传文件成功");
				result.setData(map);
				logger.info(request.getRemoteHost() + " 执行上传文件成功！");
			} else {
				logger.error(request.getRemoteHost() + " 执行上传文件失败！");
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}
	
	/**
	 * 获取文件的网络地址
	 * @return
	 */
	public static String getFileHttpUrl(String fileUrl){
		String fileHttpUrl = "";
		String fileHttp = getFilePath(FILE_HTTP);
		String fileDocBase = getFilePath(FILE_DOCBASE);
		if(fileUrl !=null && fileUrl.indexOf(fileDocBase) != -1){
			fileHttpUrl = fileHttp+fileUrl.replace(fileDocBase, "");
		}
		return fileHttpUrl;
	}
	
}
